package cn.schoolwow.quickserver.util;

import cn.schoolwow.quickserver.domain.Client;
import cn.schoolwow.quickserver.exception.HttpStatusException;
import cn.schoolwow.quickserver.response.HttpStatus;
import com.alibaba.fastjson.JSON;

import java.io.ByteArrayInputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class ExceptionHandlerUtil {
    /**
     * 处理请求过程中产生的异常
     * */
    public static void handleExceptionHandler(Client client, Throwable e) {
        if (e instanceof InvocationTargetException) {
            e = ((InvocationTargetException) e).getTargetException();
        }
        client.httpResponseMeta.httpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        if( e instanceof HttpStatusException){
            HttpStatusException httpStatusException = (HttpStatusException) e;
            client.httpResponseMeta.httpStatus(httpStatusException.getHttpStatus());
        }
        if(null == client.serverConfigMeta.exceptionHandler){
            if(!(e instanceof HttpStatusException)&&!(e instanceof SocketException)){
                e.printStackTrace();
            }
            client.httpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR);
            client.httpResponseMeta.result = e.getMessage();
            if(null==client.httpResponseMeta.result){
                client.httpResponseMeta.result = "空指针异常!";
            }
        }else{
            Object result = client.serverConfigMeta.exceptionHandler.beforeBodyWrite(e, client.httpRequest, client.httpResponse, client.httpSession);
            if (null != result) {
                client.httpResponseMeta.result = JSON.toJSONString(result);
            }
        }
        client.httpResponseMeta.contentType = "application/json";
        byte[] bytes = client.httpResponseMeta.result.getBytes(StandardCharsets.UTF_8);
        client.httpResponseMeta.contentLength = bytes.length;
        client.httpResponseMeta.bodyInputStream = new ByteArrayInputStream(bytes);
    }
}